import axios from 'axios'

const namespaced = true

const state = {
  topGainers: [],
  topLosers: [],
  recommendations: [],
  isFirstLoad: true
}

const mutations = {
  SET_TOP_GAINERS(state, stocks) {
    state.topGainers = stocks
  },
  SET_TOP_LOSERS(state, stocks) {
    state.topLosers = stocks
  },
  SET_RECOMMENDATIONS(state, stocks) {
    state.recommendations = stocks
  },
  SET_FIRST_LOAD(state, status) {
    state.isFirstLoad = status
  }
}

const actions = {
  async fetchStockData({ commit, state }) {
    try {
      if (state.isFirstLoad) {
        commit('SET_LOADING', true, { root: true })
        await new Promise(resolve => setTimeout(resolve, 300))
      }
      
      const response = await axios.get('http://localhost:3000/api/stocks')
      commit('SET_TOP_GAINERS', response.data.topGainers)
      commit('SET_TOP_LOSERS', response.data.topLosers)
      commit('SET_RECOMMENDATIONS', response.data.recommendations)
      
      commit('SET_FIRST_LOAD', false)
    } catch (error) {
      console.error('获取股票数据失败:', error)
    } finally {
      setTimeout(() => {
        commit('SET_LOADING', false, { root: true })
      }, 200)
    }
  }
}

export default {
  namespaced,
  state,
  mutations,
  actions
} 